import {useLoginStorage} from "@/stores/loginStorage.js";
import {ElMessage} from "element-plus";


const baseUrl = "http://localhost:8000/";

/**
 * 发起请求底层封装 fetch
 *
 * @param url {string} 包含 PathVariable
 * @param method {string}
 * @param params {{key: value}, null, undefined}
 * @param body {{ket: value}, null, undefined}
 */
const request = (url, method, params = null, body = null) => {
    const loginStore = useLoginStorage();

    url = (url.startsWith('/') ? baseUrl.slice(0, -1) : baseUrl) + url;

    if (params !== null && params !== undefined) {
        url += '?';
        for (const key in params)
            url += `${key}=${params[key]}&`;
        // 防止{}空对象
        if (url.endsWith('?') || url.endsWith('&'))
            url = url.slice(0, -1);
    }

    const init = {
        mode: 'cors',
        // credentials: 'include',
        method: method,
        headers: {
            'Content-Type': 'application/json',
            [loginStore.getTokenInfo.tokenName]: loginStore.getTokenInfo.tokenValue,
        },
    }

    if (body !== null && body !== undefined)
        init['body'] = JSON.stringify(body);

    console.log("params: ", params, "\nbody: ", body);

    return fetch(url, init).then(response => {
        if (response.status === 401) {
            ElMessage.error('登录状态错误');
            loginStore.$reset();
            return;
        }
        if (!response.ok) {
            ElMessage.warning('服务维护中！');
            throw new Error(`响应失败===>【${response.status}：${response.statusText}】`);
        }

        return response.json();
    }).catch(error => {
        console.error(error);
    });
}


export default request;


